package com.df.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class WebsocketServer extends Thread{

    public EventLoopGroup bossGroup = new NioEventLoopGroup();
    public EventLoopGroup workGroup = new NioEventLoopGroup();

    public void startServer(){
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new WebSocketChannelInnitailizer());

        ChannelFuture future = bootstrap.bind(9999).syncUninterruptibly();
        future.addListener((ChannelFutureListener) future1 -> {
            if(future1.isSuccess()){
                System.out.println("启动成功！");
            }else {
                System.out.println("启动失败："+future1.cause());
            }
        });
        future.syncUninterruptibly();
    }

    public void stopServer(){
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }

    @Override
    public void run() {
        startServer();
    }
}
